import * as THREE from "../../../modules/three/three.module.js";
import {flatten, toFixedVector} from "../lib/util/StaticMethods.js";
import {mapCodeToCssColor, mapColorCssToCode} from "../lib/CommonConsts.js";

let convexAreaCount = 0;
export function setAreaMarkedCount(num) {
  if (convexAreaCount <= num) {
    convexAreaCount = num + 1;
  }
}

export default class ConvexAreaVO {
  id = 0
  color = '#e86833'
  name = ""
  /**
   * 相机位置 姿态数组
   * @type {number[][]}
   */
  cameraStates = []
  /**
   * 切割顶点序列
   * @type {THREE.Vector3[]}
   */
  cutPoints = []
  /**
   * 切割折线几何对象
   * @type {THREE.BufferGeometry[]}
   */
  cutLineGeometries = []
  /**
   * 区域网格的几何对象
   * @type {THREE.BufferGeometry}
   */
  areaGeometry


  constructor() {
    this.id = convexAreaCount++
    this.name = 'convex ' + this.id
  }

  toJsonObj() {
    const obj = {id: this.id, pos: [], index: [], cutLines: [], cutPoints: []};
    obj.color = mapColorCssToCode.get(this.color) || 'unsupportedColor, ' + this.color;
    obj.cameraStates = this.cameraStates;
    this.cutPoints.forEach(point => {
      toFixedVector(point, 3);
      obj.cutPoints.push(point.toArray());
    });
    const posArray = this.areaGeometry.attributes.position.array;
    const indexArray = this.areaGeometry.index.array;
    for (let i = 0; i < posArray.length; i++) {
      const n = posArray[i].toFixed(3);
      obj.pos.push(parseFloat(n));
    }
    for (let i = 0; i < indexArray.length; i++) {
      obj.index.push(indexArray[i]);
    }
    this.cutLineGeometries.forEach(lineGeometry => {
      const array = lineGeometry.getAttribute('position').array;
      const cutLine = [];
      for (let i = 0; i < array.length; i++) {
        const n = array[i].toFixed(3);
        cutLine.push(parseFloat(n));
      }
      obj.cutLines.push(cutLine);
    });
    return obj;
  }

  fromJsonObj(jsonObj) {
    setAreaMarkedCount(jsonObj.id)
    this.id = jsonObj.id
    this.color = mapCodeToCssColor.get(jsonObj.color) || '#000000'
    this.cameraStates = jsonObj.cameraStates
    jsonObj.cutPoints.forEach(arr => {
      this.cutPoints.push(new THREE.Vector3().set(...arr))
    })
    const areaGeometry = new THREE.BufferGeometry()
    areaGeometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(jsonObj.pos), 3))
    areaGeometry.setIndex(jsonObj.index)
    this.areaGeometry = areaGeometry;
    jsonObj.cutLines.forEach(arr => {
      const lineGeo = new THREE.BufferGeometry()
      lineGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(arr), 3))
      this.cutLineGeometries.push(lineGeo)
    })
    return this;
  }
}

